package com.wuyou.mid;

import java.util.Arrays;

/**
 * 1802. 有界数组中指定下标处的最大值
 */
public class MaxValue {

    public static void main(String[] args) {
        int n = 6, index = 1, maxSum = 10;

        System.out.println(solution_1(n, index, maxSum));
    }

    public static int solution_1(int n, int index, int maxSum) {
        int avg = maxSum / n;
        int remain = maxSum % n;
        int[] nums = new int[n];
        Arrays.fill(nums, avg);
        int left = index - 1, right = index + 1, count = 1;
        while (left >= 0 || right <= nums.length - 1) {
            if (left >= 0) {
                if(left == index - 1){
                    nums[left] = nums[index] - 1;
                    remain += nums[index] + nums[left];
                }else if (nums[left] - count > 0) {
                    nums[left] -= count;
                    remain += count;
                }else {
                    int abs = Math.abs(nums[left] - nums[left + 1]);
                    if (Math.abs(nums[left] - abs) <= 1) {
                        nums[left] -= abs;
                        remain += abs;
                    }
                }
            }
            if(right == index + 1){
                nums[right] = nums[index] - 1;
                remain += nums[index] + nums[right];
            }else if (right < nums.length) {
                if (nums[right] - count >= 0) {
                    nums[right] -= count;
                    remain += count;
                } else {
                    int abs = Math.abs(nums[right] - nums[right - 1]);
                    if (Math.abs(nums[right] - abs) <= 1) {
                        nums[right] -= abs;
                        remain += abs;
                    }
                }
            }
            right++;
            left--;
            count++;
        }

        return nums[index] += (remain / n);
    }


    public static boolean checkNums(int[] nums, int remain) {
        boolean flag = true;
        for (int i = 0; i < nums.length - 1; i++) {
            if (Math.abs(nums[i] - nums[i + 1]) > 1) {
                if (remain > 0) {
                    nums[i]++;
                    remain--;
                }
                return false;
            }
        }
        return true;
    }
}
